package com.hyyt.shopjsp.statistics.controller;

import com.hyyt.shopjsp.common.controller.BaseController;
import com.hyyt.shopjsp.order.vo.ShopOrdersListVo;
import com.hyyt.shopjsp.order.service.IShopOrdersListService;
import com.hyyt.shopjsp.util.common.EnumUtils;
import com.hyyt.shopjsp.util.common.Page;
import com.hyyt.shopjsp.util.common.ResultMsg;
import com.hyyt.shopjsp.util.common.Utils;
import com.hyyt.shopjsp.util.export.ExportExcel;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 刘超 on 2017/7/19.
 */
@Controller
@RequestMapping("/back/productStatistics")
public class ProductStatisticsController extends BaseController {

    private Logger logger = Logger.getLogger(CustomerStatisticsController.class);
    private String basePath = "/back/shop/statistics/";

    @Resource
    private IShopOrdersListService shopOrdersListService;

    /**
     * 跳转商品统计页面
     *
     * @return 返回到指定页面
     */
    @RequestMapping("gotoPaidReturnProduct")
    public String gotoPaidReturnProduct(){
        return basePath + "productStatisticsList";
    }

    /**
     * 商品统计列表
     * @param page
     * @param response
     * @param createTimeStart   开始时间
     * @param createTimeEnd     结束时间
     * @param productName       商品名称
     */
    @RequestMapping(value="listProductStatistics",method= RequestMethod.POST)
    @ResponseBody
    public void listProductStatistics(Page page,String createTimeStart,String createTimeEnd,String productName,HttpServletResponse response){
        Map<String, Object> params=new HashMap<>();
        if(Utils.objectIsNotEmpty(productName)){
            params.put("productFullName", productName.trim());
        }
        if(Utils.objectIsNotEmpty(createTimeStart)){
            params.put("createTimeStart", createTimeStart);
        }
        if(Utils.objectIsNotEmpty(createTimeEnd)){
            params.put("createTimeEnd", createTimeEnd);
        }
        int totalRecordCount =shopOrdersListService.countProductStatistics(params);
        page.setPageInfo(page.getPageSize(), totalRecordCount, page.getCurrentPage());
        List<ShopOrdersListVo> shopOrdersListList=shopOrdersListService.queryProductStatistics(params, page.getPageRecordBeginIndex(), page.getPageSize());
        params.clear();
        params.put("total", totalRecordCount);// total键 存放总记录数，必须的
        params.put("rows", shopOrdersListList);// rows键 存放每页记录 list
        ResultMsg.create(params, response);  //把内容发送到页面
    }


    /**
     * 导出商品统计excel
     * @param createTimeStart
     * @param createTimeEnd
     * @param productName
     * @param request
     * @param response
     */
    @RequestMapping("exportProductStatisticsExcel")
    public void exportProductStatisticsExcel(String createTimeStart, String createTimeEnd, String productName, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        Map<String, Object> params=new HashMap<>();
        if(Utils.objectIsNotEmpty(productName)){
            productName=new String(productName.trim().getBytes("ISO-8859-1"),"UTF-8");
            params.put("productFullName", productName);
        }
        if(Utils.objectIsNotEmpty(createTimeStart)){
            params.put("createTimeStart", createTimeStart);
        }
        if(Utils.objectIsNotEmpty(createTimeEnd)){
            params.put("createTimeEnd", createTimeEnd);
        }
        List<ShopOrdersListVo> shopOrdersListList=shopOrdersListService.queryProductStatistics(params);
        SimpleDateFormat formatter = new SimpleDateFormat(EnumUtils.DataFormat.Y_M_D_H_m_s.getValue());
        List<Map<String,Object>> productStatistics = new ArrayList<>();
        if(shopOrdersListList!=null&&shopOrdersListList.size()>0){
            for (ShopOrdersListVo shopOrdersListVo : shopOrdersListList) {
                Map<String,Object> map = new HashMap<>();
                map.put("productFullName", shopOrdersListVo.getProductFullName());
                map.put("soldCount", shopOrdersListVo.getSoldCount());
                map.put("soldPrice", shopOrdersListVo.getSoldPrice());
                if(Utils.objectIsNotEmpty(shopOrdersListVo.getRefundCount())){
                    map.put("refundCount", shopOrdersListVo.getRefundCount());
                }else{
                    map.put("refundCount","0");
                }
                map.put("refundPrice", shopOrdersListVo.getRefundPrice());
                productStatistics.add(map);
            }
        }
        String fileName ="商品统计";
        String columnNames[] = {"商品名称","已付款商品数量（个）","已付款商品金额（元）","已退货商品数量（个）","已退货商品金额（元）"};
        String keys[] = {"productFullName","soldCount","soldPrice","refundCount","refundPrice"};
        try {
            ExportExcel.download(fileName,productStatistics,columnNames,keys,request,response);
        } catch (IOException e) {
            logger.error("导出Excel失败！");
        }
    }

}
